package com.ifinc.common.socket.server;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-30
 * Time: 00:47
 */

import com.ifinc.common.socket.parser.JsonDispatcher;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息处理类
 */

public class MessageHandler extends SimpleChannelHandler {

    private NettyServer nettyServer;

    private JsonDispatcher jsonDispatcher;

    @Autowired
    public void setNettyServer(NettyServer nettyServer) {
        this.nettyServer = nettyServer;
    }

    @Override
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
        nettyServer.addChannel(e.getChannel());
    }

    @Autowired
    public void setJsonDispatcher(JsonDispatcher jsonDispatcher) {
        this.jsonDispatcher = jsonDispatcher;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
            throws Exception {
        System.err.println("e.getMessage():" + e.getMessage());
        ChannelBuffer buf = (ChannelBuffer) e.getMessage();
//        String result = jsonDispatcher.doDispatch(buf.array());
//        byte[] b_result = result.getBytes();
        ChannelBuffer channelBuffer = ChannelBuffers.buffer(100);
        channelBuffer.writeBytes("OK".getBytes());
        e.getChannel().write(channelBuffer);
//        e.getChannel().close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {

//        super.exceptionCaught(ctx, e);
        System.out.println(e.getCause());

    }

}
